package org.example.util;

import lombok.extern.slf4j.Slf4j;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.lock.SetWithLock;

import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Slf4j
public class ChannelContextUtil {

    public static List<ChannelContext> contextList(Collection<String> userIds) {
        return userIds.stream().map(ChannelContextUtil::contextList).flatMap(Collection::stream).collect(Collectors.toList());
    }

    public static List<ChannelContext> contextList(String userId) {

        SetWithLock<ChannelContext> users = Tio.getByUserid(ImConfig.get().tioConfig, userId);
        if (users == null) {
            return new ArrayList<>();
        }
        return convertChannel(users);
    }

    public static List<ChannelContext> groupUsers(String roomId) {
        SetWithLock<ChannelContext> users = Tio.getByGroup(ImConfig.get().tioConfig, roomId);
        if (users == null) {
            return new ArrayList<>();
        }
        return convertChannel(users);
    }

    private static List<ChannelContext> convertChannel(SetWithLock<ChannelContext> channelContextSetWithLock) {
        ReentrantReadWriteLock.ReadLock lock = channelContextSetWithLock.getLock().readLock();
        try {
            lock.lock();
            Set<ChannelContext> channelContexts = channelContextSetWithLock.getObj();
            return new ArrayList<>(channelContexts);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            lock.unlock();
        }
        return new ArrayList<>();
    }

}
